package com.biqee.service.bq.impl;

import java.math.BigDecimal;
import java.util.List;

import org.apache.log4j.Logger;

import com.biqee.model.common.BqTuanStatus;
import com.biqee.model.db.BqEstimateResult;
import com.biqee.model.db.BqTuan;
import com.biqee.service.bq.BqTuanRankService;
import com.biqee.service.bq.BqEstimateResultService;
import com.biqee.service.bq.BqQueryRelationService;
import com.biqee.service.bq.BqTuanService;
import com.biqee.util.BigDecimalUtil;

public class BqTuanRankServiceImpl implements BqTuanRankService {
	private static final Logger logger = Logger.getLogger(BqTuanRankServiceImpl.class);
	
	@Override
	public void computeRanks(BqTuan bqTuan) {
		
		// 读取聚划算活动商品
		Integer juTbItemId = bqQueryRelationService.getTbItemId(bqTuan.getId());
		if(juTbItemId == null) {
			logger.error("null juTbItemId! bqTuanId: " + bqTuan.getId());
			return;
		}

		List<BqEstimateResult> resultList = bqEstimateResultService.readBqEstimateResultsByBqTuanId(bqTuan.getId());
		if(resultList.size() < 2) {
			logger.error("estimate result list is too samll, bqTuanId: " + bqTuan.getId() + ", listSize(): " + resultList.size());
			return;
		}
		
		int rank = 1;
		for(BqEstimateResult result : resultList) {
			if(result.getScore() > 100) {
				rank++;
			}
		}
		
		logger.info("tuanId: " + bqTuan.getId() +", rank: " + rank + " out of " + resultList.size());
		BqTuanStatus bqTuanStatus = BqTuanStatus.INIT;
		BigDecimal percentBigDecimal = BigDecimalUtil.defaultDivide(new BigDecimal(rank), new BigDecimal(resultList.size()));
		double percentDouble = percentBigDecimal.doubleValue();
		if(percentDouble <= 0.33) {
			bqTuanStatus = BqTuanStatus.GOOD;
		} else if(percentDouble <= 0.66) {
			bqTuanStatus = BqTuanStatus.COMMON;
		} else {
			bqTuanStatus = BqTuanStatus.BAD;
		}
		
		bqTuanService.updateStatus(bqTuanStatus, bqTuan.getId());
		
		// 如果需要， 将来可以在此次保存 highScore，lowScore
	}
	
	private BqQueryRelationService bqQueryRelationService;

	public void setBqQueryRelationService(
			BqQueryRelationService bqQueryRelationService) {
		this.bqQueryRelationService = bqQueryRelationService;
	}
	
	private BqEstimateResultService bqEstimateResultService;

	public void setBqEstimateResultService(
			BqEstimateResultService bqEstimateResultService) {
		this.bqEstimateResultService = bqEstimateResultService;
	}
	
	private BqTuanService bqTuanService;

	public void setBqTuanService(BqTuanService bqTuanService) {
		this.bqTuanService = bqTuanService;
	}
	
	
	
}
